<?php
/**
 * Created by PhpStorm.
 * User: kevin
 * Date: 15-6-17
 * Time: 下午5:55
 */
namespace Institution\Controller;
use Think\Controller;
use Word\Controller\IndexController;;
class TaskController extends AdminController{
	protected $department;
    protected function _initialize(){
		
		parent::_initialize();
		
		$this->department = $this->getDepartmentId(UID);
	}

	public function index(){
        cookie('__forward__','index');
		$mode = C('BUSINESS_MODE');
		
		switch($mode){
			//抢单模式
			case 1:
                $config=C('SCRAMBLE_TASK');

                switch($config){
                    case 1:
                        //获取所有未分配的任务
                        $cxh = I('cxh');
                        if($cxh){
                            $map['a.cxh']=  array('EQ',"$cxh");
                        }
                        $xmmc = I('xmmc');
                        if($xmmc){
                            $map['a.xmmc']= array('LIKE',"%$xmmc%");
                        }
						
						header('Content-type:text/html;charset=utf-8');
						$cx_user_name = I('cx_user_name');
                        if($cx_user_name){                            
                            $map['b.username']= array('LIKE',"%$cx_user_name%");
                        }
						$sarea = I('sarea');
                        if($sarea){                            
                            $map['b.sarea']= array('LIKE',"%$sarea%");
                        }
						$sh_user_name = I('sh_user_name');						
                        if($sh_user_name){
                            $map['c.username']= array('LIKE',"%$sh_user_name%");
                        }
						
						$wtrname = I('wtrname');
                        if($wtrname){
                            $map['a.wtrname']= array('LIKE',"%$wtrname%");
                        }
						
						$wtdw = I('wtdw');
                        if($wtdw){
                            $map['a.wtdw']= array('LIKE',"%$wtdw%");
                        }
						
						$xmmcen = I('xmmcen');
                        if($xmmcen){
                            $map['a.xmmcen']= array('LIKE',"%$xmmcen%");
                        }
						
						$xmmcen = I('xmmcen');
                        if($xmmcen){
                            $map['a.xmmcen']= array('LIKE',"%$xmmcen%");
                        }
						
						$intime_13starttime = I('intime_13starttime');
						$intime_13endtime = I('intime_13endtime');
                        if($intime_13starttime || $intime_13starttime){
                            $map['a.intime']= array('between',array("$intime_13starttime","$intime_13endtime"));
                        }
						
						$intimestarttime = I('intimestarttime');
						$intimeendtime = I('intimeendtime');
                        if($intimestarttime || $intimeendtime){
                            $map['a.intime_13']= array('between',array("$intimestarttime","$intimeendtime"));
                        }
						
						
						$dep	= $this->getDepartmentId(UID);
						if($dep == -2)
						{
							$this->error('该用户不属于任何一个机构');
						}
//						tengjian 2017/2/21 撤销的机构下不需要显示 process_id!=15
						$map['_string'] = ' (department_id ='.$dep.' or  department_id = 0 ) and process_id!=15';
                        $Task = M('Kjcx');
						
                        $list = $this->lists_new($Task,$map);
						$process_arr=$this->get_process();   //得到该机构下的流程
						
						
						$res_g = M('Kjcx')->field('count(*) as c,cxh')->group('cxh')->select();
						$g_arr = array();
						foreach($res_g as $k=>$v){
							if($v['c']>1){
								$g_arr[] = $v['cxh'];
							}
						}
						$this->assign('g_arr', implode('，', $g_arr));
						// echo json_encode($process_arr);exit;
                        $list=$this->getMenu($list,$process_arr);   //改机构下的功能键
						$list= self::fomartFileIds($list);
                        $this->assign('map',$map);
                        $this->assign('xmmc',$xmmc);
                        $this->assign('cxh',$cxh);
                        $this->assign('_list', $list);
						
						$this->assign('sarea',$sarea);
						$this->assign('cx_user_name',$cx_user_name);
						$this->assign('sh_user_name',$sh_user_name);
						$this->assign('wtrname',$wtrname);
						$this->assign('wtdw',$wtdw);
						$this->assign('xmmcen',$xmmcen);
						$this->assign('intime_13starttime',$intime_13starttime);
						$this->assign('intime_13endtime',$intime_13endtime);
						$this->assign('intimestarttime',$intimestarttime);
						$this->assign('intimeendtime',$intimeendtime);
                        break;
                    case 2://获取抢单配置中设置，委托提交后多少小时内可以抢单
                        $time =M('option')->where(array('id'=>'2'))->getField('value');
                        $cxh = I('cxh');
                        if($cxh){
                            $map['cxh']= $cxh;
                        }
                        $xmmc = I('xmmc');
                        if($xmmc){
                            $map['xmmc']= array('LIKE',"%$xmmc%");
                        }
                        $Task = M('Kjcx');
                        $arr = $Task->where($map)->where(array('process_id'=>'-2'))->getField('id,intime');
                        $now =date('Y-m-d H:i:s');
                        $n=strtotime($now);
                        $arr_id=array();
                        foreach($arr as $k=>$v){
                            $vo=strtotime($v);
                            $hour=($n-$vo)/3600;
                            if($hour>$time){
                                $arr_id[]=$k;
                            }
                        }
                        if($arr_id){
                            $map['id']=array('not in',$arr_id);
                        }
						$dep	= $this->getDepartmentId(UID);
						if($dep == -2)
						{
							$this->error('该用户不属于任何一个机构');
						}
						$map['_string'] = ' department_id ='.$dep.' or department_id = 0';
                        $list = $this->lists($Task,$map);
                        $process_arr=$this->get_process();
                        $list=$this->getMenu($list,$process_arr);
						$list= self::fomartFileIds($list);
                        $this->assign('map',$map);
                        $this->assign('xmmc',$xmmc);
						$this->assign('cxh',$cxh);
                        $this->assign('_list', $list);
						
						$res_g = M('Kjcx')->field('count(*) as c,cxh')->group('cxh')->select();
						$g_arr = array();
						foreach($res_g as $k=>$v){
							if($v['c']>1){
								$g_arr[] = $v['cxh'];
							}
						}
						$this->assign('g_arr', implode('，', $g_arr));
						
                        break;
                    case 3://委托时选择了查新机构，提交多少小时后学校未处理可以抢单
                        $map0=array();
                        $time =M('option')->where(array('id'=>'3'))->getField('value');
                        $cxh = I('cxh');
                        if($cxh){
                            $map['cxh']= $cxh;
                            $map0['cxh']= $cxh;
                        }
                        $xmmc = I('xmmc');
                        if($xmmc){
                            $map['xmmc']= array('LIKE',"%$xmmc%");
                            $map0['xmmc']= array('LIKE',"%$xmmc%");
                        }
                        $Task = M('Kjcx');
                        $map0['process_id']=array('eq','0');
                        $map0['department_id']=array('neq','');
                        $arr = $Task->where($map0)->getField('id,intime_copy');
                        $now =date('Y-m-d H:i:s');
                        $n=strtotime($now);
                        $arr_id=array();
                        foreach($arr as $k=>$v){
                            $vo=strtotime($v);
                            $hour=($n-$vo)/3600;
                            if($hour>$time){
                                $arr_id[]=$k;
                            }
                        }
                        if($arr_id){
                            $map['id']	= array('not in',$arr_id);
                            $map2['id']	= array('in',$arr_id);//要改变状态的id
							//修改状态0变为-2
							$list['process_id'] = -2;
							$list['department_id'] = 0;
							$list['intime_copy'] = $now;
							$Task->where($map2)->save($list);
                        }
						$dep	= $this->getDepartmentId(UID);
						if($dep == -2)
						{
							$this->error('该用户不属于任何一个机构');
						}
						$map['_string'] = ' department_id ='.$dep.' or department_id = 0';
                        $list = $this->lists($Task,$map);
                        $process_arr=$this->get_process();
                        $list=$this->getMenu($list,$process_arr);
                        $list= self::fomartFileIds($list);
                        $this->assign('map',$map);
                        $this->assign('xmmc',$xmmc);
						$this->assign('cxh',$cxh);
                        $this->assign('_list', $list);
						
						$res_g = M('Kjcx')->field('count(*) as c,cxh')->group('cxh')->select();
						$g_arr = array();
						foreach($res_g as $k=>$v){
							if($v['c']>1){
								$g_arr[] = $v['cxh'];
							}
						}
						$this->assign('g_arr', implode('，', $g_arr));
                        break;
                }
				break;
			//分配模式
			case 2:
				$map['department_id'] = $this->department;
				$Task = M('Kjcx');
				$list = $this->lists($Task,$map);
				$process_arr=$this->get_process();
				$list=$this->getMenu($list,$process_arr);
				$this->assign('_list', $list);
				break;
			default:
				$error='参数错误';
				return $error;
		}
		if(isset($_GET['p'])){
			$num = ($_GET['p']-1)*10;
			$this->assign('num', $num);
		}
		//抢单模式
		$time 	= C('SCRAMBLE_TASK');
		$q_time = M('Option')->where("id='$time'")->field('value,id')->find();
		$datatime = date("Y-m-d H:i:s",time()-$q_time['value']*3600);
		$this->assign('datatime', $datatime);
		$this->assign('meta_title', '机构所有任务');
		$this->assign('depart', DEPARTMENT_ID);  //传入机构id显示新的流程号
		$this->display();
	}

	/**
	 * 填写查新报告
	 */
	public function fill_report(){
		if(IS_POST)
		{
			$id 	= intval(I('id'));
			$res 	= M('Kjcx')->find($id);
			$data 	= $_POST['post'];
			if($res && $res['process_id'] == 17) //只有在此操作的时候才可以编辑
			{
				$data['chatime'] = time();
				$rs = M('Kjcx')->where('id='.$id)->save($data);
				if($rs)
				{
					$r = M('Kjcx')->find($id);
					$AgencyId = $this->getDepartment();
					$jigou = M('Unit')->where('depart_id='.$AgencyId)->find();
					$word = new IndexController();
					$s = $word->index($r,$jigou);
					if($s)
					{
						$arr['cx_file_ids'] = $s;
						M('Kjcx')->where('id='.$id)->save($arr);
						if(cookie('__forward__') == 'mytask')
						{
							$url = U('myTask');
						}
						else
						{
							$url = U('index');
						}
						$this->success('生成报告成功!',$url);
					}
					else
					{
						$this->error('生成报告失败！');
					}
				}
				else
				{
					$this->error('生成报告失败！');
				}
			}
			else
			{
				$this->error('该条查新任务不存在！');
			}
		}
		else
		{
			$id = I('id');
			$kjcx = M('kjcx')->find($id);
			$sctype = I('sctype');
			if(!$kjcx)
			{
				$this->error('该查新信息不存在！');
			}
			else
			{
				if( $sctype == 1 )
				{
					header("Content-type: text/html; charset=utf-8");
					//var_dump($kjcx);exit;
					$word = new IndexController();
					$file_name = $word->getBG($kjcx);
					//var_dump($file_name);exit;
					if(file_exists($file_name)){
    				$fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
    				if(!file_exists($file_name)){//判断文件是否存在
    					$this->error('文件不存在！');
    				}
    				$file_size=filesize($file_name);//判断文件大小
					$file_name = iconv("utf-8","gbk",'查新委托书');
    				//返回的文件
    				Header("Content-type: application/octet-stream");
    				//按照字节格式返回
    				Header("Accept-Ranges: bytes");
    				//返回文件大小
    				Header("Accept-Length: ".$file_size);
    				//弹出客户端对话框，对应的文件名
    				Header("Content-Disposition: attachment; filename={$file_name}.docx");
    				//防止<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=16&jk=208efa6f3933ab0f&k=%B7%FE%CE%F1%C6%F7&k0=%B7%FE%CE%F1%C6%F7&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fab33396ffa8e20&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F971%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">服务器</span></a></span>瞬时压力增大，分段读取
    				$buffer=1024;
    				while(!feof($fp)){
    					$file_data=fread($fp,$buffer);
    					echo $file_data;
    				}
    				//关闭文件
    				fclose($fp);
					}
					exit;
				}
				elseif( $sctype == 99 )
				{
					header("Content-type: text/html; charset=utf-8");
				
					$word = new IndexController();
					$file_name = $word->getht($kjcx);
			
					if(file_exists($file_name)){
    				$fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
    				if(!file_exists($file_name)){//判断文件是否存在
    					$this->error('文件不存在！');
    				}
    				$file_size=filesize($file_name);//判断文件大小
					$file_name = iconv("utf-8","gbk",$kjcx['xmmc'].'-合同');
    				//返回的文件
    				Header("Content-type: application/octet-stream");
    				//按照字节格式返回
    				Header("Accept-Ranges: bytes");
    				//返回文件大小
    				Header("Accept-Length: ".$file_size);
    				//弹出客户端对话框，对应的文件名
    				Header("Content-Disposition: attachment; filename={$file_name}.docx");
    				$buffer=1024;
    				while(!feof($fp)){
    					$file_data=fread($fp,$buffer);
    					echo $file_data;
    				}
    				//关闭文件
    				fclose($fp);
					}
					exit;
				}
				else
				{
					$kjcx['intime'] = strtotime($kjcx['intime']);
					//查新机构信息
					$AgencyId = $this->getDepartment();
					$info = M('Unit')->where('depart_id='.$AgencyId)->find();
					$this->assign('info',$info);
					$this->assign('kjcx',$kjcx);
					$this->assign('pUrl',U('Task/fill_report'));
					$this->assign('meau_title','填写查新报告');
					$this->assign('time',time());
				}
			}
			$this->display();
		}
	}
	public function edit_report(){
		if(IS_POST)
		{
			$id = intval(I('id'));
			$res = M('Kjcx')->find($id);
			$data 	= $_POST['post'];
			if($res && $res['process_id'] == 11) //只有在此操作的时候才可以编辑
			{
				$data['shentime'] = time();
				$rs = M('Kjcx')->where('id='.$id)->save($data);
				if($rs)
				{
					$r = M('Kjcx')->find($id);
					$AgencyId = $this->getDepartment();
					$jigou = M('Unit')->where('depart_id='.$AgencyId)->find();
					$word = new IndexController();
					$s = $word->index($r,$jigou);
					if($s)
					{
						$arr['cx_file_ids'] = $s;
						M('Kjcx')->where('id='.$id)->save($arr);
						$this->success('生成报告成功!');
					}
					else
					{
						$this->error('生成报告失败！');
					}
				}
				else
				{
					$this->error('生成报告失败！');
				}
			}
			else
			{
				$this->error('该条查新任务不存在！');
			}
		}
		else
		{
			$id = I('id');
			$kjcx = M('kjcx')->find($id);
			if(!$kjcx)
			{
				$this->error('该查新信息不存在！');
			}
			else
			{
				$kjcx['intime'] = strtotime($kjcx['intime']);
				//查新机构信息
				$AgencyId = $this->getDepartment();
				$info = M('Unit')->where('depart_id='.$AgencyId)->find();
				$name=session('user_auth');
				$sh_name = $kjcx['shenheyuan']?$kjcx['shenheyuan']:$name['username'];
				$this->assign('info',$info);
				$this->assign('kjcx',$kjcx);
				$this->assign('sh_name',$sh_name);
				$this->assign('pUrl',U('Task/edit_report'));
				$this->assign('meau_title','修改查新报告');
				$this->assign('time',time());
			}
			$this->display('fill_report');
		}
	}
	function fomartFileIds($list){
		foreach($list as $k=> $v){
			if($v['cx_file_ids']){
				$filedsId = explode(',',$v['cx_file_ids']);
				foreach($filedsId as $kk=>$vv){
					$list[$k]['fileId'][$kk][fid] =$vv;
				}
			}
		}
		return $list;
	}
	//我的任务
	public function myTask(){
		
		cookie('__forward__','mytask');
		$process_id = I('process_id');
		$type = I('endType');
		if(!empty($process_id)){
			if($process_id != 14)
			{
				$this->error('参数错误');
			}
			$map['process_id'] = $process_id;
			$this->assign('process_id',$process_id);
			$this->assign('tags',3);
		}else{
          
			$uid = intval(session('user_auth')['role_id']);
			$maps['title'] = array("like","%机构管理员%");
			$gid=M('auth_group')->where($maps)->getField('id');
            if ($uid==1) {//判断当前登陆用户是否为机构管理员
				$map['department_id'] = $this->department;
                $map['process_id'] = array('gt',-4);
            }else{
				$map['department_id'] = $this->department;
				$map['process_id'] = array('gt',-2);
            }
		
			$this->assign('tags',2);
			
		}
		
		$this->assign('school',$map['department_id']);
		$cxh = I('cxh');
		if($cxh){
			$map['a.cxh']= array('LIKE',"%$cxh%");
		}
		$xmmc = I('xmmc');
		if($xmmc){
			$map['a.xmmc']= array('LIKE',"%$xmmc%");
		}
//		$map['user_id'] = array('EQ',UID);
				
		if ($uid==1)
		{
			$map['_string'] = ' process_id != -2 and process_id != 15';				//点了撤销的流程
		}
		else if( in_array($uid,array(105,120,121,114)) )
		{
			
			if( empty($type) )
			{
				$map['_string'] = ' (process_id != -2 and process_id != 15 and process_id != 14 and (cx_user_name='.UID.' or sh_user_name='.UID.')) or process_id=20 ';				//点了撤销的流程
			}
			else
			{
				$map['_string'] = ' process_id = 14';	//不是管理员的时候显示收费的，查新的，审核的  待修改
			}
		}
		else
		{
			
			if($process_id != 14 &&  empty($type))
			{
				
				$map['_string'] = ' sf_user_name = '.UID.' or (cx_user_name = '.UID.' AND process_id IN (10,12,17,13)) or (sh_user_name = '.UID.' AND process_id IN (11,13))';	//不是管理员的时候显示收费的，查新的，审核的  待修改
				
			}
			else
			{
				$map['_string'] = ' cx_user_name = '.UID.' AND process_id = 14';	//不是管理员的时候显示收费的，查新的，审核的  待修改
			}
		}
		
		header('Content-type:text/html;charset=utf-8');
		$cx_user_name = I('cx_user_name');
		if($cx_user_name){
			//$map['cx_user_name']= array('LIKE',"%$cx_user_name%");
			$map['b.username']= array('LIKE',"%$cx_user_name%");
		}
		$sarea = I('sarea');
		if($sarea){                            
			$map['b.sarea']= array('LIKE',"%$sarea%");
		}
		
		$sh_user_name = I('sh_user_name');						
		if($sh_user_name){
			$map['c.username']= array('LIKE',"%$sh_user_name%");
		}
		
		$wtrname = I('wtrname');
		if($wtrname){
			$map['a.wtrname']= array('LIKE',"%$wtrname%");
		}
		
		$wtdw = I('wtdw');
		if($wtdw){
			$map['a.wtdw']= array('LIKE',"%$wtdw%");
		}
		
		$xmmcen = I('xmmcen');
		if($xmmcen){
			$map['a.xmmcen']= array('LIKE',"%$xmmcen%");
		}
		
		$xmmcen = I('xmmcen');
		if($xmmcen){
			$map['a.xmmcen']= array('LIKE',"%$xmmcen%");
		}
						
		$intime_13starttime = I('intime_13starttime');
		$intime_13endtime = I('intime_13endtime');
		if($intime_13starttime || $intime_13starttime){
			$map['a.intime']= array('between',array("$intime_13starttime","$intime_13endtime"));
		}
		
		$intimestarttime = I('intimestarttime');
		$intimeendtime = I('intimeendtime');
		if($intimestarttime || $intimeendtime){
			$map['a.intime_13']= array('between',array("$intimestarttime","$intimeendtime"));
		}
				
		
		
		$Task = M('Kjcx');
		$meta_title = '正在处理的任务';
		//print_R($map);
		if($uid==1){
			$list = $this->lists_new($Task,$map);
		}else{
			//2016.11.4 显示完成的任务
			if($process_id == 14 || $type == 1 ){
				
				$list = $this->lists_new($Task,$map);
				$meta_title = '完成的任务';
			}
			else{
				//$list = $this->lists_new($Task,$map);
				$list = $this->lists_new($Task,$map,'',1);
			}
		}
		//var_dump($list);exit;
		if($list=='-1'){
			$this->error('请给用户分配权限');
		}
		$list = getRestTime($list);
		foreach($list as $l_k => $l_v )
		{
			$condition['xmmc'] = $l_v['xmmc'];
			$condition['id'] != $l_v['id'];
			$xt_list = M('Kjcx')->where('xmmc = "'.$l_v['xmmc'].'"and id !='.$l_v['id'])->find();
			
			if( is_array($xt_list)  && count( $xt_list) > 0 )
			{
				$list[$l_k]['chongfu'] = '与查新号'.$xt_list['cxh'].'名称重复';
			}
		}
		
		$res_g = M('Kjcx')->field('count(*) as c,cxh')->group('cxh')->select();
		$g_arr = array();
		foreach($res_g as $k=>$v){
			if($v['c']>1){
				$g_arr[] = $v['cxh'];
			}
		}
	
		$this->assign('g_arr', implode('，', $g_arr));

//		$arr=M('menu_conf')->select();
		$arrSchool=M('school_area')->where('school_id = '.$map['department_id'])->select();

		$process_arr=$this->get_process();
		$list=$this->getMenu($list,$process_arr);
		$list= self::fomartFileIds($list);
		$this->assign('_list', $list);
		$this->assign('map',$map);
		$this->assign('depart', DEPARTMENT_ID);  //传入机构id显示新的流程号
		$this->assign('xmmc',$xmmc);
		$this->assign('cxh',$cxh);
		$this->assign('meta_title', $meta_title);
		$this->assign('arrSchool', $arrSchool);
		$this->assign('sarea',$sarea);
		$this->assign('sh_user_name',$sh_user_name);
		$this->assign('cx_user_name',$cx_user_name);
		$this->assign('wtrname',$wtrname);
		$this->assign('wtdw',$wtdw);
		$this->assign('xmmcen',$xmmcen);
		$this->assign('intime_13starttime',$intime_13starttime);
		$this->assign('intime_13endtime',$intime_13endtime);
		$this->assign('intimestarttime',$intimestarttime);
		$this->assign('intimeendtime',$intimeendtime);
		
		if(isset($_GET['p'])){
			$num = ($_GET['p']-1)*10;
			$this->assign('num', $num);
		}
		$this->display();
	}

    //显示所有科技查新
    public function index1(){
		$map['status'] = I('get.status')?I('get.status'):-2;
		//判断业务模式
		if(C('BUSINESS_MODE') == 1){
			$where = array('agencyId'=>$this->department);
			$map['_logic'] = 'or';
			$map['_complex'] = $where;
		}elseif(C('BUSINESS_MODE')==2){
			$map['AgencyId'] = $this->department;
		}else{
			$this->error('参数不正确');
		}
		if($map['status']==1){
			$qx_id="12";
		}elseif($map['status']==2){
			$qx_id="0,13,11,17,18,20,21,16";
		}elseif($map['status']==4){
			$qx_id="14,15";
		}elseif($map['status']=='-2'){
			$qx_id="0,13,11,17,18,20,21,16";
		}else{
			$qx_id="-1";
		}
		$where_arr=$this->get_user_qx(UID,$qx_id);
		if(!empty($where_arr)) {
			$where_sql = sprintf('(%s)', implode(' OR ', array_values($where_arr)));
		}else{
			$this->error('对不起，请先对机构权限进行设置',U('Unit/process'));
		}
		if($map['status'] != '-2'){
			$string="status=".$map['status']." AND AgencyId = ".$this->department." AND ".$where_sql;
		}else{
			$string= "AgencyId = ".$this->department." AND ".$where_sql;
		}
		$process_arr=$this->get_process();
		$this->assign('process_arr',$process_arr);
		$list = M('Task')->where($string)->where($map)->join('k_kjcx ON k_task.kjcxId = k_kjcx.id')->select();//链表查询
		$menu_conf = $this->get_menu_conf();
		$this->assign('menu_conf',$menu_conf);
		foreach($list as $key => $item){
			//为每个记录，设置按钮
			if(!empty($process_arr[$item['process_id']]['task_menu']))
			{
				$tmp_vvv = explode(',',$process_arr[$item['process_id']]['task_menu']);
				foreach($tmp_vvv as $kk => $ii)
				{
					//当前按钮已经指定给部分用户
					if(!empty($menu_conf[$ii]['check_user']))
					{
						$tmp_kkk = explode(',',$menu_conf[$ii]['check_user']);
						if(!in_array(UID, $tmp_kkk))
						{
							unset($tmp_vvv[$kk]);
						}
					}
					else
					{
						//当前按钮，需要验证是否是当前用户
						if($menu_conf[$ii]['check_user_tag'] == 1)
						{
							if($item['now_user_name'] != $user_bh)
							{
								unset($tmp_vvv[$kk]);
							}
						}
					}
				}
				$item['menu_conf'] = $tmp_vvv;
			}
			$list[$key] = $item;
		}
        $this->assign('_list',$list);
        $this->display();
    }

	//撤单
	public function info($id){
		if($id){
			$Task 					    = D('Kjcx');
			$map['id'] 				    = $id;
			$data['department_id'] 	= 0;
			$data['process_id'] 	    = -2;
			$result = $Task->where($map)->save($data);
			if($result){
                $this->success('撤单成功');
			}else{
				$this->error('撤单失败');
			}
		}else{
			$this->error('参数错误');
		}
	}

	//显示机构所有的任务
	public function all(){
		$map['status'] = I('get.status')?I('get.status'):array('gt',-2);
		$Task = M('Task');
		//判断业务模式
		if(C('BUSINESS_MODE') == 1){
			$where = array('agencyId'=>$this->department);
			$map['_logic'] = 'or';
			$map['_complex'] = $where;
		}elseif(C('BUSINESS_MODE')==2){
			$map['AgencyId'] = $this->department;
		}else{
			$this->error('参数不正确');
		}
		if($map['status']==1){
			$qx_id="12";
		}elseif($map['status']==2){
			$qx_id="0,13,11,17,18,20,21,16";
		}elseif($map['status']==4){
			$qx_id="14,15";
		}else{
			$qx_id="-1";
		}
		$where_arr=$this->get_user_qx(UID,$qx_id);
		if(!empty($where_arr)) {
			$where_sql = sprintf('(%s)', implode(' OR ', array_values($where_arr)));
		}else{
			$this->error('对不起，请先对机构权限进行设置',U('Unit/process'));
		}
		$string="status=".$map['status']." AND AgencyId = ".$this->department." AND ".$where_sql;
		$process_arr=$this->get_process();
		$this->assign('process_arr',$process_arr);
		$list = M('Task')->where($string)->join('k_kjcx ON k_task.kjcxId = k_kjcx.id')->select();//链表查询
		$menu_conf = $this->get_menu_conf();
		$this->assign('menu_conf',$menu_conf);
		foreach($list as $key => $item){
			//为每个记录，设置按钮
			if(!empty($process_arr[$item['process_id']]['task_menu']))
			{
				$tmp_vvv = explode(',',$process_arr[$item['process_id']]['task_menu']);
				foreach($tmp_vvv as $kk => $ii)
				{
					//当前按钮已经指定给部分用户
					if(!empty($menu_conf[$ii]['check_user']))
					{
						$tmp_kkk = explode(',',$menu_conf[$ii]['check_user']);
						if(!in_array(UID, $tmp_kkk))
						{
							unset($tmp_vvv[$kk]);
						}
					}
					else
					{
						//当前按钮，需要验证是否是当前用户
						if($menu_conf[$ii]['check_user_tag'] == 1)
						{
							if($item['now_user_name'] != $user_bh)
							{
								unset($tmp_vvv[$kk]);
							}
						}
					}
				}
				$item['menu_conf'] = $tmp_vvv;
			}
			$list[$key] = $item;
		}
		$this->assign('_list',$list);
		$this->display('index');
	}

    /*
     * 日志查看
     */
    public function log(){
        $map['uid'] = UID;
        $list = M('Tasklog')->select();
        $this->assign('list', $list);
        $this->display();
    }
    //处理指派任务
    public function step1(){
        if(IS_POST){

        }else{
//          $list = M('Task')->where($map)->select();
			$status=I('status')?I('status'):5;
			if($status==1){
				$qx_id="12";
			}elseif($status==2){
				$qx_id="-1";
			}elseif($status==3){
				$qx_id="15";
			}else{
				$qx_id="0,13,11,17,18,20,21,16";
			}
			$where_arr=$this->get_user_qx(UID,$qx_id);
			$where_sql = sprintf('(%s)',implode(' OR ',array_values($where_arr)));

			$string="status=$status AND AgencyId = ".$this->department." AND ".$where_sql;
// 			echo $string;exit;
			$process_arr=$this->get_process();
			$this->assign('process_arr',$process_arr);
         	$list = M('Task')->where($string)->join('k_kjcx ON k_task.kjcxId = k_kjcx.id')->select();//链表查询
         	$menu_conf = $this->get_menu_conf();
			$this->assign('menu_conf',$menu_conf);

            foreach($list as $key => $item){
            	//为每个记录，设置按钮
            	if(!empty($process_arr[$item['process_id']]['task_menu']))
            	{
            		$tmp_vvv = explode(',',$process_arr[$item['process_id']]['task_menu']);
            		foreach($tmp_vvv as $kk => $ii)
            		{
            			//当前按钮已经指定给部分用户
            			if(!empty($menu_conf[$ii]['check_user']))
            			{
            				$tmp_kkk = explode(',',$menu_conf[$ii]['check_user']);
            				if(!in_array(UID, $tmp_kkk))
            				{
            					unset($tmp_vvv[$kk]);
            				}
            			}
            			else
            			{
            				//当前按钮，需要验证是否是当前用户
            				if($menu_conf[$ii]['check_user_tag'] == 1)
            				{
            					if($item['now_user_name'] != $user_bh)
            					{
            						unset($tmp_vvv[$kk]);
            					}
            				}
            			}
            		}
            		$item['menu_conf'] = $tmp_vvv;
            	}
            	$list[$key] = $item;
            }
            $this->assign('list',$list);
            $this->display('');
        }
    }

    /*
     * 管理员指派任务页面
     */
    public function call($id){
		//判断该订单是否还在未接状态
        $tag=I('tag');
		$check = $this->checkTaskStatus($id);
		if($check){
			$this->error('对不起，该业务已经别人领取了！');
		}
		$Task = D('Kjcx');
		//指派业务
		$res = $Task->call($id, $this->department);
		action_log('grab_task','Task',$id,$this->getDepartment());
		if($res){
            if($tag=='1') {
                $this->redirect('Task/index');
            }else{
                $this->redirect('Task/myTask');
            }
		}else{
			$this->error('操作失败!');
		}
    }

    /*
     * 撤销任务
     */
    public function callback($id){
        $data = array(
            'id'=>$id,
            'department'=>null,
            'status'=>1,
            'is_push'=>null
        );
        $res = D('Task')->callback($data);
        if($res){
            D('Tasklog')->update(UID,"撤销",$data['id']);
            $this->success('撤销任务成功',U('Task/index'));
        }else{
            $this->error('撤销任务失败',U('Task/step1'));
        }
    }
    
    /************cp***************/
    /******ajax 处理******/
    public function ajax_control(){
    	$action	=	I('action');
    	$form	=	I('form');
    	switch($action)
    	{
	    	case 'get_kjcx_message'://查新申请
	    		$this->get_kjcx_message($form,UID);
	    		$arr 					= array();
	    		$arr['contents'] 		= $this->get_ajax_message;
	    		$arr['type']			= $this->get_ajax_type;

				if(!empty($form['menu_id']))   //2016.6.15  teng 添加一个标题显示
				{
					$arr['title']			= M('MenuConf')->where('department_id = '.DEPARTMENT_ID.' and  id='.$form['menu_id'])->getField('title') ;
				}
	    		echo json_encode($arr);
	    	break;
	    	case 'update_kjcx_contents'://更新查新数据
				$return_tag 			= $this->update_kjcx_contents($form,UID);
				$arr 					= array();
				$arr['state'] 			= $return_tag;
				$arr['return_message'] 	= $this->return_mess;
				$arr['contents'] 		= $this->get_ajax_message;
				echo json_encode($arr);
	    	break;
	    	case 'tj_kjcx_contents': //科技查新受理
			//print_R($form);die;
	    		if($this->tj_task($form,$user_name))
	    		{
					echo json_encode(['state'=>1,'contents'=>$this->return_mess]);
	    		}
	    		else
	    		{
	    			echo json_encode(['state'=>0,'contents'=>$this->return_mess]);
	    		}
				
	    	break;
	    	case 'tj_cx_files':
	    		$this->update_files_message('',$form);
	    		$arr 					= array();
	    		$arr['contents'] 		= $this->get_ajax_message;
	    		echo json_encode($arr);
	    	break;
	    	case 'down_file':
	    		$this->down_file();
	    	break;
            case 'cx_chedan':
                $id=I('id');
                $this->info($id);
                break;
    	}
    	
    }
    /******ajax 处理******/
    
  	//  编辑任务
    public function kjcx_edit(){
		$id = I('get.id');
		if(IS_POST){
			$data = I('post.');
			//var_dump($data);exit;
			if($data['xkfl'] == ''){
				$this->error('请选择学科');
				return false;
			}
			if(($data['cxfw'] == 2 || $data['cxfw'] == 3)  && $data['xmmcen'] == ''){
				$this->error('请填写项目英文名称');
				return false;
			}
			if(in_array(1,$data['cxmd'])  && $data['xxcxmd'] == ''){
				$this->error('请填写详细查新目的');
				return false;
			}
			if($data[cxmd]){$data[cxmd]=implode(',',$data[cxmd]);}//将查新目的格式化存到数组中
			if($data[cxyq]){$data[cxyq]=implode(',',$data[cxyq]);}//将查新要求格式化存到数组中
			$array = $this->prove_array();
			foreach($array as $key=>$vo){
				if($data[$vo['title']] == ''){
					$this->error($vo['msg']);
					return false;
				}
			}
			if(($data['cxfw'] == 2 || $data['cxfw'] == 3)  && $data['keywords_en'] == ''){
				$this->error('请填写外文检索词');
				return false;
			}

			if(empty($data)){
				return false;
			}
			if(empty($data['id'])){
				$id = M('Kjcx')->add();
				if(!$id){
					M('Kjcx')->error = '添加任务失败';
					return false;
				}
			}else{
				//var_dump($data);exit;
				$data = M('Kjcx')->create($data);
				
				$res = M('Kjcx')->save($data);
				if($res){
					$this->success('更新成功',U('index'));
				}else{
					$this->error('更新失败');
				}
			}
		}else{
			$id 	= intval(I('id'));
			$task   = M('Kjcx')->find($id);
			//var_dump($task);exit;
			if(!$task)
			{
				$this->error('数据不存在');
			}
			else
			{
				//根据学科id得到对应的所有二级学科
				$subject_er = M('SchoolMore')->find($task['xkfl']);
				$task['subject_yj'] = $subject_er['fid'];
				$sub_arr = M('SchoolMore')->where("fid=$subject_er[fid] and status=1")->getField('id,title');
				$this->assign('sub_arr', $sub_arr);
				$this->assign('info', $task);
				$sqfj_arr = explode(',', $task['sqfj']);
				$sqfj_arr_new = array();
				//显示附件名称
				if (!empty($sqfj_arr)) {
					foreach ($sqfj_arr as $k => $vo) {
						if ($vo != '') {
							$m = M('Attachment')->where('id=' . $vo)->field('id,title')->find();
							$sqfj_arr_new[$k]['title'] = $m['title'];
							$sqfj_arr_new[$k]['id'] = $m['id'];
						}
					}
				}
				$this->assign('sqfj_arr', $sqfj_arr_new);
				$this->assign('cxmd_arr', explode(',', $task['cxmd']));
				$upload_ids_arr = explode(',', $task['upload_ids']);
				$this->assign('upload_ids_arr', $upload_ids_arr);
				//得到查新机构
				if ($task['department_id'] != '') {
					
					$jigou = M('Department')->where('id=' . $task['department_id'])->getField('name');
					//var_dump($task['department_id']);exit;
					$this->assign('jigou', $jigou);
				}
				//查新要求
				$this->assign('cxyq', explode(',', $task['cxyq']));

				if(I('tag'))
				{
					$this->assign('tag', intval(I('tag')));
				}

				$this->display();
			}
		}
    }

    public function kjcx_browser(){
		$id 	= intval(I('id'));
		$task   = M('Kjcx')->find($id);
		//var_dump($task);exit;
		if(!$task)
		{
			$this->error('数据不存在');
		}
		else
		{
			$this->assign('info', $task);
			$sqfj_arr = explode(',', $task['sqfj']);
			$sqfj_arr_new = array();
			//显示附件名称
			if (!empty($sqfj_arr)) {
				foreach ($sqfj_arr as $k => $vo) {
					if ($vo != '') {
						$m = M('Attachment')->where('id=' . $vo)->field('id,title')->find();
						$sqfj_arr_new[$k]['title'] = $m['title'];
						$sqfj_arr_new[$k]['id'] = $m['id'];
					}
				}
			}
			$this->assign('sqfj_arr', $sqfj_arr_new);
			$upload_ids_arr = explode(',', $task['upload_ids']);
			$this->assign('upload_ids_arr', $upload_ids_arr);
			if(I('tag'))
			{
				$this->assign('tag', intval(I('tag')));
			}
			$this->display();
		}

	}
    
    //获取机构馆员
    private function get_jg_user(){
    	$depart_id=M('department')->where("uid=".UID)->getField('id');
    	$user_list=M('user')->field('username,id')->where("department=".$depart_id.' AND id <> '.UID)->select();
    	return $user_list;
    }
    //获取机构下的流程
    private function get_process(){
		$werhe_arr		=array('tag'=>1,'department_id'=>DEPARTMENT_ID);
    	$process_list=M('CxProcess')->where($werhe_arr)->getField('process_id,title,show_user_id,check_user,show_button_tag,check_user_tag,task_menu');
//		echo M('CxProcess')->getLastSql();exit;
    	return $process_list;
	}
    //获取机构下可执行功能
    private function get_menu_conf(){
    	$fun_id=M('MenuConf')->where('department_id ='.DEPARTMENT_ID)->getField('id,title,check_user,check_user_tag,js_fun,tj_ts,control_type,js_fun_param,update_field,ts_message,type,param,process_id,show_button_tag,update_tag');
    	return $fun_id;
    }
     
    
    public function funmenu(){
    	$list=M('MenuConf')->where()->order('id ASC')->select();
    	$this->assign('list',$list);
    	$this->display();
    }
    
    
    
    //获取科技查新信息
	var $get_ajax_message = array();
	var $get_ajax_type	  = '';
	public function get_kjcx_message($arr,$user_bh)
	{
		$task_one_message		=	$this->get_one_message($arr['task_id']);
		if(!empty($task_one_message))
		{
			$menu_conf=$this->get_menu_conf();
			if(!empty($menu_conf[$arr['menu_id']]))
			{
				
				if(preg_match('/^system_user/siU',$menu_conf[$arr['menu_id']]['js_fun']))//获取人员列表
				{
					$user = M('User');
					if($arr['menu_id'] == 12){
						$list=$user->where("department=$this->department and typeid in (104,105,120)")->field('username,id')->select();
					}else{
						$list=$user->where("department=$this->department")->field('username,id')->select();
					}
//					$list=M('User')->field('username,id')->where("department=$this->department")->select();
					$this->get_ajax_message=$list;
				}
				else if($menu_conf[$arr['menu_id']]['js_fun'] == 'log')//获取日志
				{
					$list=M('LogKjcx')->field('user_bh,ip,intime,process_id,contents')->where('`task_id` = '.$arr['task_id'])->select();
					foreach($list as $key=>$vo){
						$list[$key]['user_bh'] = getUsernameByUid($vo['user_bh']);
						$list[$key]['process_id'] = get_process_name1($vo['process_id'] );
					}
					$this->get_ajax_message=$list;
					$this->get_ajax_type = 'log';
				}
				else if($menu_conf[$arr['menu_id']]['js_fun'] == 'sf_log')//收费日志
				{
					$list=M('LogSf')->where('`cx_id` = '.$arr['task_id'])->order('intime')->select();
					$this->get_ajax_message=$list;
					$this->get_ajax_type = 'sf_list';
				}				
				else if($menu_conf[$arr['menu_id']]['js_fun'] == 'cx_file_ids' || $menu_conf[$arr['menu_id']]['js_fun'] == 'sh_file_ids')//获取附件
				{
					$file_arr = $task_one_message[$menu_conf[$arr['menu_id']]['js_fun']];
					if(!empty($file_arr))
					{
						$this->get_ajax_message = $this->get_file_message($file_arr);
					}
				}
				else if($menu_conf[$arr['menu_id']]['js_fun'] == 'create_cx_report')//创建查新报告
				{
					$this->get_doc_file($arr['task_id'],'查新报告',$user_bh);
				}
				else if($menu_conf[$arr['menu_id']]['js_fun'] == 'get_kjcx_sf' || $menu_conf[$arr['menu_id']]['js_fun'] == 'get_kjcx_add_sf' || $menu_conf[$arr['menu_id']]['js_fun'] == 'get_sf_zt')
				{
					$this->get_ajax_message = $task_one_message;
				}
				else 
				{
					$tmp_v = explode(',',$menu_conf[$arr['menu_id']]['js_fun']);
					foreach($tmp_v as $v)
					{
						if(!empty($v))
						{
							$this->get_ajax_message[$v] = $task_one_message[$v];
						}
					}
					$this->get_ajax_message['id'] = $task_one_message['id'];
				}
			}
		}
	}
    
    
	/**
	 * 更新内容
	 */
	public function update_kjcx_contents($arr = array(),$user_bh = '')
	{
		$task_one_message	=	$this->get_one_message($arr['task_id']);
		$arr_k=M('Kjcx')->where('cxh="'.$arr['cxh'].'" and id<>'.$arr['task_id'])->find();
		//dump(M('Kjcx')->getLastSql());die;
		if(count($arr_k)>0){
			$this->return_mess = '查新号已存在！ ';
			return 2;
		}
		if(!empty($task_one_message))
		{
			$menu_conf		=	$this->get_menu_conf();
			$process_list	=	$this->get_process();//获取业务流程
			if(!empty($menu_conf[$arr['menu_id']]))
			{
				$tmp_v		= $menu_conf[$arr['menu_id']];
				$tmp_q 		= json_decode(htmlspecialchars_decode($tmp_v['ts_message']),true);
				switch($tmp_v['js_fun'])
				{
					case 'create_cx_report'://创建查新报告电子版
					$file_name = $arr['file_name'];
					if(!empty($file_name))
					{
						$file 		= sprintf('../../upload/cx_file/lib/%s_%s.html',$arr['task_id'],$file_name);
						$file 		= iconv("UTF-8", "GB2312//IGNORE", $file);
							
						if(!file_exists($file))
						{
							$content 	= file_get_contents('html_tpl/default/kjcx/tpl/doc.html');

							preg_match_all('/\{\{(.*)\}\}/siU',$content,$arr_1);
							$tmp_arr = array();
							foreach($arr_1[1] as $key_1 => $item_1)
							{
								$tmp_arr[$item_1] = 1;
							}

							$tmp_value	= $task_one_message;

							foreach($tmp_arr as $key => $item)
							{
								if(isset($tmp_value[$key]) )
								{
									$content = str_replace('{{'.$key.'}}',$tmp_value[$key],$content);
								}
							}

							file_put_contents($file, $content);

							//将信息插入附件表中
							$insert_arr 			= array();
							$insert_arr['cx_id'] 	= $arr['task_id'];
							$insert_arr['user_bh'] 	= $user_bh;
							$insert_arr['file_name']= $arr['file_name'];
							$insert_arr['intime'] 	= date('Y-m-d H:i:s');
							$insert_arr['tag'] 		= 0;
							$insert_arr['type'] 	= '查新报告';

							//$this->DB->insert_table_message($this->get_t_name(203),$insert_arr);
						}
						else
						{
							$this->return_mess = '文件已经存在 ';
						}
					}
					else
					{
						$this->return_mess = '文件名不能为空';
							
					}

					//$this->get_doc_file($arr['task_id'],'查新报告',$user_bh);

					return 0;
					break;
					case 'get_kjcx_add_sf'://添加收费
					$insert_arr 				= array();
					$insert_arr['cx_id'] 		= $arr['task_id'];
					$insert_arr['fy'] 			= $arr['zzfy'];
					$insert_arr['abs'] 			= $arr['shyy'];
					$insert_arr['intime']		= date('Y-m-d H:i:s');
					$insert_arr['ip']			= get_client_ip();
					$insert_arr['user_name'] 	= $user_bh;
					$insertId =M('LogSf')->data($insert_arr)->add();
					if($insertId)
					{
						$sf_id 		= $insertId;
						$return_tag	=	M('Kjcx')->where('id ='.$arr['task_id'])->setInc('zfy',$arr['zzfy']);
						if($return_tag  !== false)
						{
							$this->return_mess .= "\r\n".$tmp_q['update_ok'];
							$this->return_log_meg= @$tmp_q['ok_log'];
							return 1;
						}
						else
						{
							$return_tag= M('LogSf')->where('id='.$sf_id)->delete();
							$this->return_mess .= "\r\n".$tmp_q['update_error'];
							$this->return_log_meg= @$tmp_q['error_log'];
							return 0;
						}
					}
					else
					{
						$this->return_mess .= "\r\n".$tmp_q['update_error'];
						$this->return_log_meg= @$tmp_q['error_log'];
						return 0;
					}

					break;
					default:
					$mr_arr 		= array('menu_id','task_id');
					$update_arr 	= array();
					$last_update_arr=array();
					if(!empty($tmp_v['update_field']))
					{
						$tmp_www  = json_decode(htmlspecialchars_decode($tmp_v['update_field']),true);
						foreach($tmp_www as $kkk => $iii)
						{
							switch($iii['type'])
							{
								case 'self':
									$update_arr[$kkk] = $iii['value'];
									break;
								case 'input':
									$update_arr[$kkk] = $arr[$iii['value']];
									break;
							}
							$last_update_arr[$kkk] = $task_one_message[$kkk];
						}
					}
					else
					{
						foreach($arr as $key => $item)
						{
							if(!in_array($key, $mr_arr))
							{
								$last_update_arr[$key] = $task_one_message[$key];
								$update_arr[$key] = $item;
							}
						}
					}
					if(count($update_arr)>0)
					{
						if($update_arr['bh_contents']){
							action_log('reject_task','Task',$arr['task_id'],UID,$update_arr['bh_contents']);
						}
						$return_tag	=	M('Kjcx')->where('id ='.$arr['task_id'])->save($update_arr);
						if($return_tag  !== false)
						{
							$tag = $this->tj_task($arr,$user_bh);//更新后，判断是否有提交的操作
							$tmp_q	= json_decode(htmlspecialchars_decode($tmp_v['ts_message']),true);
							if($tag)//没有提交
							{
								$this->return_mess .= "\r\n".$tmp_q['update_ok'];
								$this->return_log_meg= @$tmp_q['ok_log'];
								return 1;
							}
							else
							{
								$this->return_log_meg= @$tmp_q['error_log'];
								return 0;
							}
						}
						else
						{
							$this->return_mess .= "\r\n".$tmp_q['update_error'];
							$this->return_log_meg= @$tmp_q['error_log'];
							return $return_tag;
						}
					}
					else
					{
						$this->return_mess .= "\r\n".$tmp_q['update_error'];
						$this->return_log_meg= @$tmp_q['error_log'];
						return 0;
					}
					break;
				}
			}
		}
	}
	
	/**
	 * 用户提交任务
	 */
	var $return_mess = '';
	public function tj_task($arr  = array(),$user_bh = '')
	{
		$tag = false;
		$task_one_message	=	$this->get_one_message($arr['task_id']);
		if(!empty($task_one_message))
		{
			$menu_conf		=	$this->get_menu_conf();
			$process_list	=	$this->get_process();//获取业务流程
		//print_r($menu_conf);die;
			if(!empty($menu_conf[$arr['menu_id']]))
			{
				$tmp_v = $menu_conf[$arr['menu_id']];
				switch($tmp_v['control_type'])
				{
					case 'tj'://提交
					case 'fc':
						if($arr['menu_id'] == 124){
							M('Kjcx')->where('id ='.$task_one_message['id'])->delete();
							$this->return_mess = "操作成功！";
							$this->return_log_meg= $tmp_q['ok_log'];
							$tag = true;
						}else{
							
							if(!empty($process_list[$tmp_v['process_id']]))
							{

								//判断提交前后的流程是否一致
								if($tmp_v['process_id'] != $task_one_message['process_id'] && $tmp_v['process_id'] != '')
								{
									//判断是否验证相关变量
									if(!empty($tmp_v['update_tag']))
									{
										$tmp_q 		= json_decode(htmlspecialchars_decode($tmp_v['update_tag']),true);
										if(is_array($tmp_q))
										{
											//不判断审核人员是否为空
											foreach($tmp_q as $k=>$v){
												if($k=='sh_user_name'){
													unset($tmp_q[$k]);
												}
											}
											unset($tmp_q['sh_user_name']);
											$return_tag = $this->check_rule($tmp_q,$task_one_message);
											if($return_tag)
											{
												$update_arr 				= array();
												$update_arr['process_id'] 	= $tmp_v['process_id'];
												$return_tag	=	M('Kjcx')->where('id ='.$task_one_message['id'])->save($update_arr);
												if($tmp_v['process_id']=='14'){
													M('Task')->where('kjcxId ='.$task_one_message['id'])->save(array('status'=>4));
												}
												$tmp_q 						= json_decode(htmlspecialchars_decode($tmp_v['ts_message']),true);
												if($return_tag !== false)
												{
													$this->tj_update_control($tmp_v,$arr,$task_one_message['id']);
													$this->return_mess .= "\r\n".$tmp_q['tj_ok'];
													$this->return_log_meg= $tmp_q['ok_log'];
													if($process_list[$tmp_v['process_id']]['email_tag'] == 1){$this->send_email_user($tmp_v['process_id']);}
													$tag = true;
												}
												else
												{
													$this->return_mess .= "\r\n".$tmp_q['tj_error'];
													$tag = false;
												}
											}
											else
											{
												//不符合提交条件1
											}
										}
										else
										{
											$this->return_mess = '检测格式出错，请联系管理员';
										}
									}
									else
									{
										$update_arr 				= array();
										$update_arr['process_id'] 	= $tmp_v['process_id'];
										$update_arr['intime_13'] 	= date('Y-m-d H:i:s',time());
										$return_tag	=	M('Kjcx')->where('id ='.$task_one_message['id'])->save($update_arr);
										$tmp_q 						= json_decode(htmlspecialchars_decode($tmp_v['ts_message']),true);
										if($return_tag !== false)
										{
											$this->return_mess .= "\r\n".$tmp_q['tj_ok'];
											$this->return_log_meg= $tmp_q['ok_log'];
											//$this->tj_update_control($tmp_v);
											if($process_list[$tmp_v['process_id']]['email_tag'] == 1){$this->send_email_user($tmp_v['process_id']);}
											$tag = true;
										}
										else
										{
											$this->return_mess .= "\r\n".$tmp_q['tj_error'];
											$tag = false;
										}
									}
								}
								else
								{
									$tmp_q 	= json_decode(htmlspecialchars_decode($tmp_v['ts_message']),true);
									$this->return_mess = "操作成功！";
									$this->return_log_meg= $tmp_q['ok_log'];
									$tag = true;
								}
							}
							else
							{
								$this->return_mess = sprintf('提交的流程编号“%d”不存在',$tmp_v['process_id']);
							}
						}
					break;
				}
			}
			else
			{
				$this->return_mess = '当前的操作功能不存在';
			}
			$this->save_log(UID,$arr['task_id'],$tag,$tmp_v['process_id']);
		}
		return $tag;
	}
	
	function tj_update_control($tmp_v = array(),$arr=array(),$task_id='')
	{
		$update_arr = array();
		if(!empty($tmp_v['update_field']))
		{
			$tmp_www  = json_decode(htmlspecialchars_decode($tmp_v['update_field']),true);
			foreach($tmp_www as $kkk => $iii)
			{
				switch($iii['type'])
				{
					case 'self':
						$update_arr[$kkk] = $iii['value'];
						break;
					case 'input':
						$update_arr[$kkk] = $arr[$iii['value']];
						break;
				}
	
			}
			$return_tag	=	M('Kjcx')->where('id ='.$task_id)->save($update_arr);
		}
	}
	
	
    //组装sql语句
    function get_user_qx($user_bh = '',$qx_ids='0')
    {
    	$process_list	=	$this->get_process();//获取业务流程
    	$tmp_v 		= explode(',',$qx_ids);
    	$where_arr 	= array();
    	//获取用户当前的任务流程信息
    	foreach($tmp_v as $v)
    	{
    		if(!empty($process_list[$v]))
    		{
    			$tmp_value = $process_list[$v];
    			//全显账号
    			if(!empty($tmp_value['show_user_id']))
    			{
    				$tmp_kkk = explode(',',$tmp_value['show_user_id']);
    				if(in_array($user_bh, $tmp_kkk))
    				{
    					$where_arr[] = sprintf('( `k_kjcx`.`process_id` = %d)',$v);
    				}
    			}
    			if(!empty($tmp_value['check_user']))
    			{
    					
    				//无需要测试当前用户，适用于值班人员
    				if($tmp_value['check_user_tag'] == 0 || empty($tmp_value['show_button_tag']) )
    				{
    					$tmp_kkk = explode(',',$tmp_value['check_user']);
    
    					if(in_array($user_bh, $tmp_kkk))
    					{
    						$where_arr[] = sprintf('( `k_kjcx`.`process_id` = %d)',$v);
    					}
    				}
    				else
    				{
    					//当前流程需要检测当前用户
    					$tmp_v = json_decode(htmlspecialchars_decode($tmp_value['show_button_tag']),true);
    					foreach($tmp_v as $key => $item)
    					{
    						switch($item['type'])
    						{
    							case 'session_user':
    								$tmp_arr 		= array();
    								$tmp_arr[] 		= sprintf('`k_kjcx`.`process_id` = %d',$v);
    								$tmp_arr[] 		= sprintf('`k_kjcx`.`%s` = "%s"',$key,$user_bh);
    								$where_arr[] 	= sprintf('( %s)',implode(' AND ',$tmp_arr));
    								break;
    						}
    					}
    
    				}
    			}
    		}
    	}
    	return $where_arr;
    }
    
    /**
     * 获取一条任务
     * @param number $id
     */
    public function get_one_message($id = 0)
    {
    	$list=M('Kjcx')->where('id='.$id)->find();
    	return $list;
    }
    

    /**
     * 获取附件详细信息
     */
    function get_file_message($file_arr = '')
    {
    	if(empty($file_arr)){
			$file_arr = '0';
		}else{
			$file_arr = trim($file_arr,',');
		}
		
		$list=M('Attachment')->where('`id` IN ('.$file_arr.')')->getField('id,title,create_time');
    	return $list;
    }
    
    /**
     * 系统自动发送邮件
     */
    function send_email_user($process_id = 0)
    {
    	$return_tag = $this->DB->get_query_one_arr($this->get_t_name(171),array('process_id'=>$process_id));
    	if($return_tag)
    	{
    		$arr 		= $this->DB->return_message[0];
    		$user_email = $arr['send_email'];
    		$subject 	= $arr['send_email_title'];
    		$content    = $arr['email_content'];
    			
    		//需要获取字段对应的中名称
    		$sql = sprintf('SELECT * FROM `%s` ',$this->get_t_name(200));
    		$res = $this->DB->run_sql($sql);
    		$tmpf= array();
    		if($res)
    		{
    			while($row = mysql_fetch_assoc($res))
    			{
    				$tmpf[$row['field_title']] = $row['field_value'];
    			}
    		}
    			
    		$user_email  = @$task_one_message[@$tmpf[$user_email]];
    			
    		//替换正文内容
    		foreach($tmpf as $key => $item)
    		{
    			$content = str_replace('【'.$key.'】',@$task_one_message[@$tmpf[$item]],$content);
    		}
    		$this->send_email($user_email,$content,$subject);
    	}
    }
    
    /**
     * 检测规则
     *
     */
    function check_rule($rolu = array(),$message = array())
    {
    	foreach($rolu as $key => $item)
    	{
    		switch($item['rule'])
    		{
    			case 'check_empty':
    				if(empty($message[$key]))
    				{
    					$this->return_mess = $item['error_message'];
    					return false;
    				}
    				break;
    			case 'check_eq':
    				if($message[$key] == $item['value'])
    				{
    					$this->return_mess = $item['error_message'];
    					return false;
    				}
    				break;
    		}
    	}
    	return true;
    }
    
    /**
     * 更新上传的附件
     */
    function update_files_message($user_bh = '',$arr = array())
    {
    	$task_one_message	=	$this->get_one_message($arr['task_id']);
    	if(!empty($task_one_message))
    	{
			$menu_conf		=	$this->get_menu_conf();
    		if(!empty($menu_conf[$arr['menu_id']]))
    		{
    			if($arr['type'] == 'add')
    			{
    				$file_arr = $task_one_message[$menu_conf[$arr['menu_id']]['js_fun']];
    					
    				if(empty($file_arr)){$file_arr = $arr['files_id'];}
    				else
    				{
    					$file_arr .= ','.$arr['files_id'];
    				}
    			}
    			else
    			{
    				$file_arr = $arr['files_id'];
    			}

    			$this->get_ajax_message = $this->get_file_message($file_arr);
    			$update_arr[$menu_conf[$arr['menu_id']]['js_fun']]=$file_arr;
    			$return_tag	=	M('Kjcx')->where('id ='.$arr['task_id'])->save($update_arr);
    		}
    	}
    }
    
    /**
     * 保存日志
     * @param string $user_bh  	当前用户操作编号
     * @param number $task_id	操作任务编号
     * @param number $status	操作状态
     * @param string $log_message	操作信息
     */
    function save_log($user_bh = '',$task_id = 0,$status = 0,$process_id = 0)
    {
    	$insert_arr					= array();
    	$insert_arr['ip'] 			= get_client_ip();
    	$insert_arr['intime']		= date('Y-m-d H:i:s');
    	$insert_arr['user_bh']		= $user_bh;
    	$insert_arr['task_id']		= $task_id;
    	$insert_arr['contents']		= $this->return_log_meg;
    	$insert_arr['process_id']	= $process_id;
    	if($insert_arr['contents']!=''){
    		$insertId =M('LogKjcx')->data($insert_arr)->add();
//			M('ActionLog')->data($insert_arr)->add();
			switch($insert_arr['process_id']){
				case '20':
					$actionName = "auditing_task";
					break;
				case '16':
					$actionName = 'allot_task';
					break;
				case '17':
					$actionName = 'pay_money';
					break;
				case '21':
					$actionName = 'allot_over';
					break;
				case '13':
					$actionName = 'finish';
					break;
			}
			action_log($actionName,'Task',$insert_arr['task_id'],UID);
    	}
    }
	public function upload(){
		$upload = new \Think\Upload();// 实例化上传类
		$upload->maxSize   =     3145728 ;// 设置附件上传大小
		$tmp_can	=	$_GET['can']?$_GET['can']:0;
		if($tmp_can==1){
			$upload->exts      =     array('jpg','png','jpeg','gif','bmp');// 设置附件上传类型
		}else{
			$upload->exts      =     array('doc', 'rar','zip','docx','pdf');// 设置附件上传类型
		}
		$upload->rootPath  =     './uploads/user/'; // 设置附件上传根目录
		$upload->savePath  =     ''; // 设置附件上传（子）目录
		$tmp_name	=	$_GET['tmp_name']?$_GET['tmp_name']:'icoA';

		// 上传文件
		$info   =   $upload->upload();
		if(!$info) {// 上传错误提示错误信息
			echo json_encode(array('state'=>$upload->getError()));
		}else{// 上传成功
			//print_R($info);exit;
			$file=array(
				'uid'=>UID,
				'title'=>$info[$tmp_name]['name'],
				'title_r'=>$info[$tmp_name]['savename'],
				'type'=>'1',
				'size'=>$info[$tmp_name]['size'],
				'dir'=>$upload->rootPath.$info[$tmp_name]['savepath'],
				'create_time'=>date('Y-m-d H:i:s')
			);
			$id = M('Attachment')->add($file);
			echo json_encode(array('state'=>'ok','upload_id'=>$id,'base_file_n'=>$file['title']));
		}
	}

    
    public function down_file(){
		
    	$file_id=$_GET['file_id'];
    	if(empty($file_id)){
    		redirect("文件不存在跳转页面");
    	}else{//如果要加登录条件，这里可以自己加
    		$map['id'] = $file_id;
    		$list=D('Attachment')->where($map)->select();
    		if ($list == false) {//文件不存在，可以跳转到其它页面
    			header('HTTP/1.0 404 Not Found');
    			header('Location: .');
    		} else {
				$stitle = $list[0]['title_r']?$list[0]['title_r']:$list[0]['title'];
    			$file_name="./".$list[0]['dir'].$stitle;//需要下载的文件
				
    			$file_name=iconv("utf-8","gb2312","$file_name");
    			if(file_exists($file_name)){
    				$fp=@fopen($file_name,"r+");//下载文件必须先要将文件打开，写入内存
    				if(!file_exists($file_name)){//判断文件是否存在
    					$this->error('文件不存在！');
    				}
    				$file_size=filesize($file_name);//判断文件大小
    				//返回的文件
    				Header("Content-type: application/octet-stream");
    				//按照字节格式返回
    				Header("Accept-Ranges: bytes");
    				//返回文件大小
    				Header("Accept-Length: ".$file_size);
    				//弹出客户端对话框，对应的文件名
    				Header("Content-Disposition: attachment; filename=".$list[0]['title']);
    				//防止<span id="2_nwp" style="width: auto; height: auto; float: none;"><a id="2_nwl" href="http://cpro.baidu.com/cpro/ui/uijs.php?c=news&cf=1001&ch=0&di=128&fv=16&jk=208efa6f3933ab0f&k=%B7%FE%CE%F1%C6%F7&k0=%B7%FE%CE%F1%C6%F7&kdi0=0&luki=3&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=fab33396ffa8e20&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F971%2Ehtml&urlid=0" target="_blank" mpid="2" style="text-decoration: none;"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">服务器</span></a></span>瞬时压力增大，分段读取
    				$buffer=1024;
    				while(!feof($fp)){
    					$file_data=fread($fp,$buffer);
    					echo $file_data;
    				}
    				//关闭文件
    				fclose($fp);
    			}else{
    				$this->error('文件不存在！');
    			}
    
    		}
    	}
    }
    
    /*************cp***************/


	protected function getDepartmentByUID(){
		$user = M('User');
		$departmentId = $user->find(UID);
		return $departmentId['department'];
	}

	//判断该业务是否还在未处理状态
	private function checkTaskStatus($id){
		return D('Kjcx')->checkStatus($id);
	}
	private function getMenu($list,$process_arr){
		$menu_conf = $this->get_menu_conf();
		
		$this->assign('menu_conf',$menu_conf);
		//得到每个机构的收费人员，查新人员，审核人员 的id		待修改  2016.7.15 teng
		$show_id = M('MenuConf')->where('title = "分配收费人员" and department_id ='.DEPARTMENT_ID)->getField('id');
		// $cha_id = M('MenuConf')->where('title = "分配查新人员" and department_id ='.DEPARTMENT_ID)->getField('id');
		// $shen_id = M('MenuConf')->where('title = "分配审核人员" and department_id ='.DEPARTMENT_ID)->getField('id');
		foreach($list as $key => $item){
			//为每个记录，设置按钮
//			ECHO UID;exit;
			
			
			if(!empty($process_arr[$item['process_id']]['task_menu']))
			{
				$tmp_vvv = explode(',',$process_arr[$item['process_id']]['task_menu']);
				
				foreach($tmp_vvv as $kk => $ii)
				{
					
							//当前按钮已经指定给部分用户
					if(!empty($menu_conf[$ii]['check_user']))
					{
						$tmp_kkk = explode(',',$menu_conf[$ii]['check_user']);
						if(!in_array(UID, $tmp_kkk))
						{
							unset($tmp_vvv[$kk]);
						}
					}
					else
					{
						//当前按钮，需要验证是否是当前用户
						if($menu_conf[$ii]['check_user_tag'] == 1)
						{
							if($item['now_user_name'] != $user_bh)
							{
								unset($tmp_vvv[$kk]);
							}
						}
					}

					//如果指定过后收费，查新和审核人员就不显示  2016.6.15 teng 此处代码需改进
					if($item['sf_user_name'] != '' && $ii == $show_id )
					{
						unset($tmp_vvv[$kk]);
					}
					if($item['cx_user_name'] != '' && $ii == $cha_id)
					{
						unset($tmp_vvv[$kk]);
					}
					if($item['sh_user_name'] != '' && $ii == $shen_id)
					{
						unset($tmp_vvv[$kk]);
					}
					
				}
				
				foreach( $tmp_vvv as $t_k => $t_v )
				{
					if( $t_v == 6 )
					{
						$bohui = $t_v;
						unset($tmp_vvv[$t_k]);
						$tmp_vvv[] = $bohui;
					}
				}
				
				
				$item['menu_conf'] = $tmp_vvv;
				
			}
			
			$list[$key] = $item;
			
		}
		
		return $list;
	}

	/**
	 * 验证数组  2016.6.8 teng
	 */
	protected function prove_array()
	{
		$array = array(
			array('title'=>'xmmc',          'value'=>' ',     'msg'=>'请填写项目中文名称'),
			array('title'=>'cxmd',          'value'=>' ',     'msg'=>'请选择查新目的'),
			array('title'=>'xmjb',          'value'=>' ',     'msg'=>'请选择项目级别'),
			array('title'=>'show_add_cxd',  'value'=>' ',     'msg'=>'请填写查新点'),
			array('title'=>'jsd',           'value'=>' ',     'msg'=>'请填写技术要求'),
			array('title'=>'cxyq',          'value'=>' ',     'msg'=>'请选择查新要求'),
			array('title'=>'lqrq',          'value'=>' ',     'msg'=>'请填写完成日期'),
			array('title'=>'keywords_cn',   'value'=>' ',     'msg'=>'请填写中文检索词'),
			array('title'=>'wtr_name',      'value'=>' ',     'msg'=>'请输入委托人'),
		);
		return $array;
	}

	/**
	 * 根据用户id得到机构id
	 * 2016.6.30  teng
	 */
	protected function getDepartmentId ($id)
	{
		$result = M('User')->where('id='.$id)->getField('department');
		if(!$result)
		{
			return -2;
		}
		else
		{
			return $result;
		}
	}
}